<?php 
namespace app\common\service;

use app\admin\model\SystemAdmin;


class WeginService
{
    /**
     * 检测当前是否在微擎框架中
     *
     * @return boolean true 微擎模块 false 脱离微擎,独立版
     */
    public static function isMicroEngine()
    {
        global $_W;
        return !empty($_W['uniacid']);
    }

    /**
     * 获取微擎模块标识
     */
    public static function getModuleName()
    {
        global $_W;
        return $_W['current_module']['name'] ?? '';
    }

    public static function getAdminUserId()
    {
        global $_W;
        return self::isMicroEngine() ? $_W['user']['uid']  : '';
    }
    /**
     * 获取微擎平台 uniacid
     */
    public static function getUniacid()
    {
        global $_W;
        return $_W['uniacid'] ?? '0';
    }

    /**
     * 返回包含微擎uniacid的数组
     * 
     * @param   $data 附加数据
     * @example uniacid();
     * @example uniacid($data);
     */
    public static function uniacid($data = null)
    {
        global $_W;
        $uniacid = self::isMicroEngine() ? ['uniacid' => $_W['uniacid']] : [];
        return is_null($data) ? $uniacid : array_merge($uniacid, $data);
    }

    public static function openid()
    {
        global $_W;
        $openid = request()->post('openid');
        if(!empty($openid)){
            return $openid;
        }
        return $_W['openid'] ?? '';
    }

    /**
     * 获取微擎平台appid和开发者密钥
     */
    public static function getPlatConfig()
    {
        if (self::isMicroEngine()) {
            global $_W;
            $account = [
                'appid'  => $_W['account']['key'],
                'secret' => $_W['account']['secret'],
            ];
        } else {
            $account = [
                'appid'  => ConfigLogic::getValueBykey('appid'),
                'secret' => ConfigLogic::getValueBykey('secret'),
            ];
        }
        return array_values($account);
    }

    /**
     * 获取微信支付所需配置
     */
    public static function getPaymentConfig(&$app_id, &$mch_id, &$key, &$cert_path, &$key_path)
    {
        if (self::isMicroEngine()) {
            global $_W;
            $app_id = $_W['account']['key'];
        } else {
            $app_id = ConfigLogic::getValueBykey('appid');
        }
        $mch_id    = ConfigLogic::getValueBykey('mch_id');
        $key       = ConfigLogic::getValueBykey('mch_key');
        $cert_path = ConfigLogic::getValueBykey('cert_path');
        $key_path  = ConfigLogic::getValueBykey('key_path');
    }

    /**
     * 获取public目录的访问路径
     */
    public static function getAccessPublic()
    {
        if (self::isMicroEngine()) {
            return implode('/', ['', 'addons', self::getModuleName(), 'public/']);
        } else {
            return '/';
        }
    }

    // +----------------------------------------------------------------------
    // | 文件存储相关
    // +----------------------------------------------------------------------

    /**
     * 获取本地文件存储目录(绝对路径)
     */
    public static function getLocalStorageDir()
    { 
        if (self::isMicroEngine()) {          
            return ATTACHMENT_ROOT . self::getModuleName() . '/' . self::getUniacid();
        } else {
            return public_path() . 'storage';
        }
    }

    /**
     * 获取本地文件访问前缀(Url前缀)
     */
    public static function getFileAccessPrefix()
    {
        if (self::isMicroEngine()) {
            return implode('/', ["", 'attachment', self::getModuleName(), self::getUniacid(), '']);
        } else {
            return implode('/', ["", 'storage', '']);
        }
    }

    /**
     * 获取云存储文件存放目录
     *
     * @param string $prefix 自定义存放目录前缀
     */
    public static function getCloudStoragePath(string $prefix = 'storage')
    {
        if (self::isMicroEngine()) {
            // 微擎
            return implode('/', [self::getModuleName(), self::getUniacid(), date('Ymd')]);
        } else {
            // 独立版
            return ($prefix ? $prefix . '/' : '') . date('Ymd');
        }
    }

    /**
     * 根据图片绝对路径地址转为URL地址
     *
     * @param string $root 图片绝对路径地址
     */
    public static function geImgUrlByRoot(string $root)
    {
        $domain = request()->domain();
        if (self::isMicroEngine()) {
            // 微擎
            $image = mb_substr($root, mb_strrpos($root, 'attachment'));
        } else {
            // 独立版
            $image = mb_substr($root, mb_strrpos($root, 'storage'));
        }
        return $domain . '/' . $image;
    }
    /** 
     * 微擎后台进来后先判断是否有必要的参数，没有就新建
     * @return void
     */
    public static function checkInstall()
    {
        global $_W;
        $uniacid = self::getUniacid();
        if (!self::isMicroEngine() || empty($uniacid))  return;
        $wuid = self::getAdminUserId();
        $no_admin = SystemAdmin::where('uniacid', $uniacid)->where('wuid', $wuid)->find() ;
        if(empty($no_admin)){
            SystemAdmin::create([
                'uniacid'=> $uniacid, 
                'wuid'=> $wuid,
                'username'=> $_W['user']['username'],
                'password'=> password( random(6)),
            ]);
        }
    }
}
